package com.black.service.service;

import com.alibaba.fastjson2.JSONObject;
import com.black.protocol.Response;
import com.black.service.dao.ServerDao;
import com.black.service.entity.MenuEntity;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ServerServiceImpl implements ServerService {

    final ServerDao serverDao;

    public ServerServiceImpl(ServerDao serverDao) {
        this.serverDao = serverDao;
    }

    @Override
    public Response<?> info() {
        JSONObject result = new JSONObject();
        result.put("status", "正常运行");
        result.put("count", serverDao.count());
        return Response.success(result);
    }

    @Override
    public Response<?> menuList() {
        List<MenuEntity> menuEntities = serverDao.menuList();
        List<MenuEntity> parentMenu = menuEntities.stream().filter(menuEntity -> menuEntity.getParentId() == 0).collect(Collectors.toList());
        for (MenuEntity menuEntity : parentMenu) {
            buildMenuTree(menuEntity, menuEntities);
        }
        return Response.success(parentMenu);
    }

    private void buildMenuTree(MenuEntity menuEntity, List<MenuEntity> menuEntities) {
        List<MenuEntity> children = menuEntities.stream().filter(menu -> menu.getParentId() == menuEntity.getId()).collect(Collectors.toList());
        if (children.isEmpty()) {
            return;
        }
        menuEntity.setChildren(children);
        for (MenuEntity child : children) {
            buildMenuTree(child, menuEntities);
        }
    }
}
